<template>
  <div class="resource-edit">
    <div class="page-header">
      <h2>{{ isEdit ? '编辑资源' : '新增资源' }}</h2>
    </div>

    <el-card class="edit-card">
      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="100px"
        v-loading="loading"
      >
        <el-form-item label="资源类型" prop="type">
          <el-radio-group v-model="form.type">
            <el-radio label="ARTICLE">文章</el-radio>
            <el-radio label="VIDEO">视频</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="标题" prop="title">
          <el-input v-model="form.title" placeholder="请输入资源标题" />
        </el-form-item>

        <el-form-item label="作者" prop="author">
          <el-input v-model="form.author" placeholder="请输入作者" />
        </el-form-item>

        <el-form-item label="简介" prop="summary">
          <el-input
            v-model="form.summary"
            type="textarea"
            :rows="3"
            placeholder="请输入资源简介"
          />
        </el-form-item>

        <!-- 文章内容编辑器 -->
        <el-form-item 
          v-if="form.type === 'ARTICLE'" 
          label="文章内容" 
          prop="content"
        >
          <el-input
            v-model="form.content"
            type="textarea"
            :rows="10"
            placeholder="请输入文章内容"
          />
        </el-form-item>

        <!-- 视频上传 -->
        <el-form-item 
          v-if="form.type === 'VIDEO'" 
          label="视频文件" 
          prop="videoUrl"
        >
          <el-upload
            class="video-uploader"
            :action="uploadUrl"
            :headers="uploadHeaders"
            :before-upload="beforeVideoUpload"
            :on-success="handleVideoSuccess"
            :on-error="handleVideoError"
            accept=".mp4,.mov,.avi"
          >
            <div v-if="!form.videoUrl" class="upload-trigger">
              <el-icon><upload-filled /></el-icon>
              <div class="upload-text">点击上传视频</div>
            </div>
            <video 
              v-else 
              :src="form.videoUrl" 
              class="video-preview" 
              controls
            />
          </el-upload>
          <div class="upload-tip">
            支持 mp4、mov、avi 格式，单个文件不超过500MB
          </div>
        </el-form-item>

        <el-form-item label="发布状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio :label="1">立即发布</el-radio>
            <el-radio :label="0">保存草稿</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="handleSubmit">保存</el-button>
          <el-button @click="handleCancel">取消</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { UploadFilled } from '@element-plus/icons-vue'
import request from '@/utils/request'
import Cookies from 'js-cookie'

const route = useRoute()
const router = useRouter()
const formRef = ref(null)
const loading = ref(false)

const isEdit = computed(() => route.params.id)

// 表单数据
const form = ref({
  type: 'ARTICLE',
  title: '',
  author: '',
  summary: '',
  content: '',
  videoUrl: '',
  status: 1
})

// 表单验证规则
const rules = {
  type: [{ required: true, message: '请选择资源类型', trigger: 'change' }],
  title: [{ required: true, message: '请输入标题', trigger: 'blur' }],
  author: [{ required: true, message: '请输入作者', trigger: 'blur' }],
  summary: [{ required: true, message: '请输入简介', trigger: 'blur' }],
  content: [{ 
    required: true, 
    message: '请输入文章内容', 
    trigger: 'blur',
    validator: (rule, value, callback) => {
      if (form.value.type === 'ARTICLE' && !value) {
        callback(new Error('请输入文章内容'))
      } else {
        callback()
      }
    }
  }],
  videoUrl: [{
    required: true,
    message: '请上传视频文件',
    trigger: 'change',
    validator: (rule, value, callback) => {
      if (form.value.type === 'VIDEO' && !value) {
        callback(new Error('请上传视频文件'))
      } else {
        callback()
      }
    }
  }]
}

// 视频上传相关
const uploadUrl = '/admin/resource/upload'
const uploadHeaders = {
  Authorization: Cookies.get('token')
}

const beforeVideoUpload = (file) => {
  const isValidFormat = ['video/mp4', 'video/quicktime', 'video/x-msvideo'].includes(file.type)
  const isLt500M = file.size / 1024 / 1024 < 500

  if (!isValidFormat) {
    ElMessage.error('只能上传 mp4/mov/avi 格式的视频！')
    return false
  }
  if (!isLt500M) {
    ElMessage.error('视频大小不能超过 500MB！')
    return false
  }
  return true
}

const handleVideoSuccess = (res) => {
  form.value.videoUrl = res.data
  ElMessage.success('视频上传成功')
}

const handleVideoError = () => {
  ElMessage.error('视频上传失败')
}

// 获取资源详情
const fetchResourceDetail = async (id) => {
  loading.value = true
  try {
    const { data } = await request.get(`/admin/resource/${id}`)
    form.value = data
  } catch (error) {
    console.error('Error fetching resource:', error)
    ElMessage.error('获取资源详情失败')
  } finally {
    loading.value = false
  }
}

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return
  
  try {
    await formRef.value.validate()
    
    const submitData = { ...form.value }
    if (isEdit.value) {
      await request.put(`/admin/resource/${route.params.id}`, submitData)
    } else {
      await request.post('/admin/resource', submitData)
    }
    
    ElMessage.success('保存成功')
    router.push('/admin/resources')
  } catch (error) {
    console.error('Error submitting form:', error)
    ElMessage.error('保存失败')
  }
}

// 取消
const handleCancel = () => {
  router.back()
}

onMounted(() => {
  if (isEdit.value) {
    fetchResourceDetail(route.params.id)
  }
})
</script>

<style scoped>
.resource-edit {
  padding: 20px;
}

.page-header {
  margin-bottom: 20px;
}

.edit-card {
  margin-bottom: 20px;
}

.video-uploader {
  width: 100%;
  max-width: 360px;
}

.upload-trigger {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 180px;
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  transition: border-color 0.3s;
}

.upload-trigger:hover {
  border-color: #409EFF;
}

.upload-text {
  margin-top: 8px;
  color: #666;
}

.video-preview {
  width: 100%;
  max-width: 360px;
  height: auto;
  max-height: 200px;
  object-fit: cover;
}

.upload-tip {
  font-size: 12px;
  color: #666;
  margin-top: 8px;
}
</style> 